<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/17
 * Time: 15:11
 */

namespace app\admin\controller;

use app\admin\Base;
use app\admin\model\Menus;
use think\Config;
use think\Session;
use think\Db;

class Index extends Base
{
    public function index()
    {
        //一级菜单
        $top_menus = \Rbac::getTopMenu();
//        echo "<pre>";
//        print_r($top_menus);
//        exit;
        //第一个一级菜单的二级菜单项
        $group_menus = array();
        $first = 0;
        if ($top_menus) {
            foreach ($top_menus as $k=>$item) {
                $first = $item['id'];
                $group_menus = \Rbac::getGroupMenu($item['id']);
                break;
            }
        }
        if(!empty($group_menus[$first])){
            foreach($group_menus[$first] as $k=>$v){
                $group_menus[$first][$k]['icon'] = $group_menus[$first][$k]['icon'] ? htmlspecialchars_decode($group_menus[$first][$k]['icon']) : "&#xe616;";
            }
        }
        return $this->fetch('', compact('top_menus', 'group_menus', 'first'));
    }

    public function welcome()
    {
        $top_menus = \Rbac::getTopMenu();
        // 查询 ip 地址和登录地点
        if (Session::get('last_login_time')) {
            $last_login_ip = Session::get('last_login_ip');
            $last_login_loc = \Ip::find($last_login_ip);
            $last_login_loc = implode(" ", $last_login_loc);
        }
        $current_login_ip = $this->request->ip();
        $current_login_loc = \Ip::find($current_login_ip);
        $current_login_loc = implode(" ", $current_login_loc);

        // 查询个人信息
        $info = Db::name("operator")->where("id", parent::$uid)->find();
        return $this->fetch('', compact('info', 'last_login_ip', 'last_login_loc', 'current_login_ip', 'current_login_loc', 'top_menus'));
    }
    /**
     * @todo ajax根据上级菜单id获取子级菜单
     * @param $id 上级菜单id
    */
    public function getMenu()
    {
        $id = $this->request->param("id", "");
        if (empty($id)) {
            return ajax_return_error('没有获取到一级菜单ID！');
        }
        $group_list = \Rbac::getGroupMenu($id);
        if (!$group_list) {
            ajax_return_error('没有该菜单，请核查！');
        }
        foreach($group_list[$id] as $k=>$v){
            $group_list[$id][$k]['icon'] = $group_list[$id][$k]['icon'] ? htmlspecialchars_decode($group_list[$id][$k]['icon']) : "&#xe616;";
        }
        return ajax_return($group_list);
    }

}